//-------------------------------------------------------------------------
// Copyright (c) 2000-2016 Digital. All Rights Reserved.
//
// This software is the confidential and proprietary information of
// Digital
//
// Original author: allnas
//
//-------------------------------------------------------------------------
// APACHE
//-------------------------------------------------------------------------
package com.zj.dubbo.user.service;

import com.zj.dubbo.RpcRunTimeException;
import com.zj.dubbo.entity.User;
import com.zj.dubbo.response.DubboResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

/**
 * @author zhaojin
 */
@Slf4j
@Service(group = "user-service", retries = 0, timeout = 10000)
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public DubboResponse<Integer> save(User user) {
        log.info("user:{}", user);
        String insertSql = "INSERT INTO t_user_info(user_name,password) VALUES(?,?)";
        int userId = 0;
        if (Objects.nonNull(user)) {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            jdbcTemplate.update(connection -> {
                PreparedStatement preparedStatement = connection.prepareStatement(insertSql, new String[]{"id"});
                preparedStatement.setString(1, user.getUserName());
                preparedStatement.setString(2, user.getPassword());
                return preparedStatement;
            }, keyHolder);
            userId = keyHolder.getKey().intValue();
            log.info("======>insert into t_user_info with id:[{}]", userId);
        }
        return new DubboResponse(HttpStatus.OK.value(), "success", userId);
    }

    @Override
    public DubboResponse<Integer> batchSave(List<User> users) {
        String insertSql = "INSERT INTO t_user_info(user_name,password) VALUES(?,?)";
        jdbcTemplate.batchUpdate(insertSql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                preparedStatement.setString(1, users.get(i).getUserName());
                preparedStatement.setString(2, users.get(i).getPassword());
            }

            @Override
            public int getBatchSize() {
                return users.size();
            }
        });
        return null;
    }

    @Override
    public DubboResponse<Integer> delete(int id) {
        String deleteSql = "DELETE FROM t_user_info WHERE id = ?";
        int result = jdbcTemplate.update(deleteSql, id);
        return new DubboResponse<Integer>(HttpStatus.OK.value(), "success", result);
    }

    @Override
    public DubboResponse<Integer> update(User user) {
        String updateSql = "UPDATE t_user_info SET user_name = ?,password = ? WHERE id = ?";
        int result = jdbcTemplate.update(updateSql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setString(1, user.getUserName());
                preparedStatement.setString(2, user.getPassword());
                preparedStatement.setInt(3, user.getId());
            }
        });
        return new DubboResponse<Integer>(HttpStatus.OK.value(), "success", result);
    }

    @Override
    public DubboResponse<String> check(User user) throws RpcRunTimeException {
        log.info("user:{}", user);

        String checkSql = "SELECT COUNT(*) FROM t_user_info WHERE user_name = ? AND password = ?";
        if (Objects.nonNull(user.getUserName()) || Objects.nonNull(user.getPassword())) {
            int cnt = jdbcTemplate.queryForObject(checkSql, new Object[]{user.getUserName(), user.getPassword()}, int.class);
            if (cnt > 0) {
                return new DubboResponse(HttpStatus.OK.value(), "success", "成功");
            } else {
                throw new RpcRunTimeException("请求消息不存在");
            }
        } else {
            throw new RpcRunTimeException("请求参数不合法");
        }
    }

}
